const calculator = {
  a: null,
  b: null,
  read: function () {
    this.a = Number(prompt('a?'))
    this.b = Number(prompt('b?'))
  },
  sum: function () {
    return this.a + this.b
  },
  mul() {
    return this.a * this.b
  },
}

calculator.read()
alert(calculator.sum())
alert(calculator.mul())

const Calculator = function () {
  this.a = null
  this.b = null
  this.read = function () {
    this.a = Number(prompt('a?'))
    this.b = Number(prompt('b?'))
  }
  this.sum = function () {
    return this.a + this.b
  }
  this.mul = function () {
    return this.a * this.b
  }
}

let calculator = new Calculator()
calculator.read()

alert('Sum=' + calculator.sum())
alert('Mul=' + calculator.mul())

const Accumulator = function (value) {
  this.value = value
  this.read = function () {
    this.value += +prompt('How much to add?')
  }
}

let accumulator = new Accumulator(1) // 初始值 1

accumulator.read() // 添加用户输入的 value
accumulator.read() // 添加用户输入的 value

alert(accumulator.value) // 显示这些值的总和

// const sumTo = function(n) {
//   let result = 0
//   for (let index = 1; index <= n; index++) {
//     result += index
//   }
//   return result
// }
// const sumTo = function(n) {
//   if (n === 1) {
//     return 1
//   } else {
//     return n + sumTo(n - 1)
//   }
// }
const sumTo = function (n) {
  let s = ((1 + n) * n) / 2
  return s
}
console.log(sumTo(1))
console.log(sumTo(2))
console.log(sumTo(3))
console.log(sumTo(4))
console.log(sumTo(100))

const factorial = function (n) {
  if (n === 1) {
    return 1
  } else {
    return n * factorial(n - 1)
  }
}
console.log(factorial(1))
console.log(factorial(2))
console.log(factorial(3))
console.log(factorial(4))
console.log(factorial(5))

const fib = function (n) {
  // if (n <= 1) {
  //   return n
  // } else {
  //   return fib(n - 1) + fib(n - 2)
  // }
  let a = 1
  let b = 1
  for (let index = 3; index <= n; index++) {
    let c = a + b
    a = b
    b = c
  }
  return b
  // 卧槽这就是动态规划
}
console.log(fib(1))
console.log(fib(2))
console.log(fib(3))
console.log(fib(4))
console.log(fib(5))

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null,
      },
    },
  },
}
// const printList = function(list) {
//   console.log(list.value)
//   if (list.next) {
//     printList(list.next)
//   }
// }
const printList = function (list) {
  let temp = list
  while (temp) {
    console.log(temp.value)
    temp = temp.next
  }
}
printList(list)
